<template>
<div class="goods">
  <div class="menu-wrapper" ref="menuWrapper">
    <ul class="">
      <li v-for="(item,index) in goods"
          class="menu-item"
          :class="{current:currentIndex === index}"
          @click="selectMenu(index)">
        <span class="text">
          <i v-show="item.type>0"
             class="icon" :class="classMap[item.type]"></i>
          {{item.name}}
        </span>
      </li>
    </ul>
  </div>
  <div class="foods-wrapper" ref="foodWrapper">
    <ul>
      <li v-for="item in goods"
          class="foods-list food-list-hook"
          :key="item.name">
        <h1 class="title">{{item.name}}</h1>
        <ul>
          <li v-for="(food,index) in item.foods"
              class="food-item"
              :key="index" @click="selectFood(food)">
            <div class="icon">
              <img :src="food.icon" width="57" height="57">
            </div>
            <div class="content">
              <h2 class="name">{{food.name}}</h2>
              <p class="desc">{{food.description}}</p>
              <div class="extra">
                <span class="count">月售{{food.sellCount}}份</span>
                <span>好评率{{food.rating}}%</span>
              </div>
              <div class="price">
                <span class="now">￥{{food.price}}</span>
                <span class="old" v-show="food.oldPrice">￥{{food.oldPrice}}</span>
              </div>
              <div class="cart-control-wrapper">
                <cart-control :food="food" @cartAdd="cartAdd"/>
              </div>
            </div>
          </li>
        </ul>
      </li>
    </ul>
  </div>
  <shop-cart :delivery-price="seller.deliveryPrice"
             :min-price="seller.minPrice"
             :select-foods="selectFoods" ref="shopcart"/>
  <Food :food="selectedFood" ref="food" @foodAdd="cartAdd"/>
</div>
</template>

<script>
  import BScroll from 'better-scroll'

  import ShopCart from '@/components/mainTab/shopCart/ShopCart'
  import CartControl from '@/components/mainTab/cartControl/CartControl'
  import Food from '@/components/mainTab/food/Food'


  import axios from 'axios'
  export default {
    name: "Goods",
    props: {
      seller: Object
    },
    components: {
      ShopCart,
      CartControl,
      Food
    },
    data(){
      return {
        goods: [],
        listHeight: [],
        scrollY: 0,
        menuScroll: null,
        foodScroll: null,
        selectedFood: {},
        classMap: ['decrease','discount','special','invoice','guarantee'],
      }
    },
    // 在创建完组件后通过 axios 获取goods数据
    created() {
      axios.get('/mock/data.json').then(res => {
        if(res.data){
          this.goods = res.data.goods;
          // 获取完数组之后执行下一步
          this.$nextTick(() => {
            this.initScroll(); // 创建滚动效果
            this.calculateHeight()  // 计算每个食物li的高度
          })
        }
      })
    },
    methods: {
      // 创建菜单栏的师傅列表的滚动对象
      initScroll(){
        // 1、创建BScroll对象
        this.menuScroll = new BScroll(this.$refs.menuWrapper,{
          click: true  // 设置menuScroll滚动能监听点击事件，默认是false
        });
        this.foodScroll = new BScroll(this.$refs.foodWrapper,{
          click: true,
          probeType: 3  // 该属性指定该滚动是否需要实时监听滚动位置
        });

        // 2、监听食物列表的滚动位置
        this.foodScroll.on('scroll', (position) => {
          // console.log(position);
          this.scrollY = Math.abs(Math.round(position.y));
        })
      },
      // 通过类名 food-list-hook 获取每个商品（食物）的高度，将高度保存到数组 listHeight 中
      calculateHeight(){
        const foodList = this.$refs.foodWrapper.getElementsByClassName('food-list-hook');
        let height = 0;
        this.listHeight.push(height);
        for (let i=0; i< foodList.length; i++){
          let item = foodList[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
      },
      // 点击左侧菜单栏，右侧食物列表滚动到对应的位置
      selectMenu(index){
        // 获取所有 class='food-list-hook' 的元素（存放于一个数组中）
        const foodList = this.$refs.foodWrapper.getElementsByClassName('food-list-hook');
        // 拿到索引为 index 的元素
        let el = foodList[index];
        //
        this.foodScroll.scrollToElement(el, 300);
      },
      cartAdd(target){
        this.$refs.shopcart.drop(target);
      },
      selectFood(food){
        this.selectedFood = food;
        this.$refs.food.show();
      }
    },
    computed: {
      // 根据监听到的滚动的y坐标，判断左边菜单栏应该位于哪个栏
      currentIndex(){
        for (let i=0; i< this.listHeight.length; i++){
          let height1 = this.listHeight[i];
          let height2 = this.listHeight[i+1];
          if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
            return i;
          }
        }
        return 0;
      },
      selectFoods(){
        let foods = [];
        this.goods.forEach((good) => {
          good.foods.forEach((food) => {
            if(food.count){
              foods.push(food);
            }
          });
        });
        return foods;
      }
    }
  }
</script>

<style scoped lang="stylus">
.goods
  display flex
  position absolute
  top 174px
  bottom 46px
  width 100%
  overflow hidden
  .menu-wrapper
    flex 0 0 80px
    width 80px
    background #f3f5f7
    .menu-item
      display table
      height 54px
      width 56px
      padding 0 12px
      line-height 14px
      //text-align center
      &.current
        position relative
        z-index 10
        margin-top -1px
        background #ffff
        font-weight 700
        .text
          &:after
            display none
      .icon
        display inline-block
        vertical-align top
        width 12px
        height 12px
        margin-right 2px
        background-size 12px 12px
        background-repeat no-repeat
        &.decrease
          background-image url("../../../assets/img/goods/decrease_3@2x.png")
        &.discount
          background-image url("../../../assets/img/goods/discount_3@2x.png")
        &.guarantee
          background-image url("../../../assets/img/goods/guarantee_3@2x.png")
        &.invoice
          background-image url("../../../assets/img/goods/invoice_3@2x.png")
        &.special
          background-image url("../../../assets/img/goods/special_3@2x.png")
      .text
        display table-cell
        width 56px
        vertical-align middle
        border-bottom 1px solid rgba(7,17,27,.1)
        font-size 12px
  .foods-wrapper
    flex 1
    .title
      padding-left 14px
      height 26px
      line-height 26px
      border-left 2px solid #d9dde1
      font-size 12px
      color rgb(147,153,159)
      background #f3f5f7
    .food-item
      display flex
      margin 18px
      padding-bottom 18px
      border-bottom 1px solid rgba(7,17,27,.1)
      &:last-child
        &:after
          display none
      .icon
        flex 0 0 57px
        margin-right 10px
      .content
        flex 1
        position relative
        .name
          margin 2px 0 8px 0
          height 14px
          line-height 14px
          font-size 14px
          color rgb(7,17,27)
        .desc, .extra
          line-height 10px
          font-size 10px
          color rgb(147,153,159)
        .desc
          line-height 12px
          margin-bottom 8px
        .extra
          .count
            margin-right 10px
        .price
          font-weight 700
          line-height 24px
          .now
            margin-right 18px
            font-size 14px
            color rgb(240,20,20)
          .old
            text-decoration line-through
            font-size 10px
            color rgb(147,153,159)
        .cart-control-wrapper
          position absolute
          right -16px
          bottom 12px
</style>
